// var powerlist = ["/micro/ident-group:queryList","/micro/ident-group:add"];
<!--自定义函数判断权限-->
var userInfo = getAuthority();
var powerlist = JSON.parse(userInfo).permissions;
/*自定义函数判断权限*/
template.defaults.imports.hasPower = function(data){
    if(powerlist.includes(data)){
        return true;
    }
    return false;
};

layui.use(['layer', 'form', 'table', 'util', 'dtree','laypage'], function () {
    var $ = layui.jquery;
    var layer = layui.layer;
    var form = layui.form;
    var table = layui.table;
    var util = layui.util;
    var dtree = layui.dtree;
    var admin = layui.admin;
    var laypage = layui.laypage;

    var Authorization;//请求接口用
    var count = 0;//总个数
    var current=1;//当前页
    var fistRenderPage= true;//是否第一次渲染分页
    var gid = '';//枚举id
    var vid = '';//版本值id
    var IdentValueTree = [];//存放分组值树数据
    var IdentValueSelected = {};//分组值树选中节点
    var dirrid;//暂存目录id
    var parCode;//暂存上级code
    var par_id;//暂存上级id
    var menuDetails;//暂存选中目录信息
    var menuGroup;//暂存选中目录分组
    var groupName = '';//搜索的名称
    var loadTree = [];//存储已加载的树形上级节点id
    //获取权限方法
    if(userInfo){
        var access_token = localStorage.getExpire("access_token");
        var token_type = localStorage.getExpire("token_type");
        Authorization = token_type+" "+access_token;
        getMenuGroupList();
    }

    var setting={//树设置
        identValueSetting:{//区划树设置
            edit: {
                enable: true,
                showRemoveBtn: false,
                showRenameBtn: false,
                drag: {
                    isCopy: true,
                    isMove: false,
                    prev: false,
                    next: false,
                    inner: false
                }
            },
            data: {
                key: {
                    children: "sub",
                    isParent: "isParent",
                    title: "name"
                },
                simpleData: {
                    enable: true
                }
            },
            callback: {
                onExpand: onExpandIdentValueTree,
                onClick: identValueOnClick
            },
            view: {
                showIcon: true,
                showLine: true
            }
        },
    }

    getMenuGroupPower();
    getMenuValuePower();

    // 添加
    $('#addMenuGroup').click(function () {
        addMenuGroupModel();
    });
    //监听行单击事件
    table.on('row(menuManage)', function(obj){
        obj.tr.addClass('layui-table-click').siblings().removeClass('layui-table-click');
        dirrid = obj.data.id
        menuDetails = '';
        menuGroup = obj.data
        $("#treeTbTree").empty();
        getTreeTable(obj.data,function (resArr) {
            $.fn.zTree.init($("#treeTbTree"), setting.identValueSetting, resArr);
        });
    });
    // 工具条点击事件
    table.on('tool(menuManage)', function (obj) {
        var data = obj.data;
        var layEvent = obj.event;
        if (layEvent === 'edit') { // 修改
            showEditModel(data);
        } else if (layEvent === 'del') { // 删除
            doDelMenuGroup(obj);
        }
    });

    // 搜索按钮点击事件
    form.on('submit(formSubSearchTbLtrt)', function (data) {
        fistRenderPage = true
        insTb.reload({where: data.field}, 'data');
    });

    // 表单弹窗-添加目录值
    $('#addMenuValueBtn').click(function () {
        showAddMenuValueModel()
    });
    $('#editMenuValueBtn').click(function () {
        showEditMenuValueModel()
    });
    $('#deleteMenuValueBtn').click(function () {
        showDeleteMenuValueModel()
    });
    // 搜索按钮点击事件
    form.on('submit(formSubSearchTbBas)', function (data) {
        groupName = data.field.groupName;
        fistRenderPage = true;
        getMenuGroupList();
    });
    //获取目录分组列表信息
    function getMenuGroupList() {
        var req={
            current: current,
            size: pageSize,
            name:groupName
        };
        axios.get(metadataUrl.menuManage.menuGroup.menuGroupList,{
            params: req,
            headers:{
                'Authorization':Authorization
            }
        })
            .then(function (response) {
                if(response.status == 200 &&response.data.message == "success"){
                    var data = response.data.data;
                    renderMenuGroupTable(data);
                }
            })
            .catch(function (error) {
            });
    }
    //渲染目录分组表格
    function renderMenuGroupTable(menuData) {
        table.render({
            elem: '#menuManage',
            size: 'sm', //小尺寸的表格
            data:menuData.records,
            page: false,
            cellMinWidth: 100,
            cols: [[
                {type:'numbers', title: '序号'},
                {field: 'name', align: 'center', title: '分组名称'},
                {field: 'memo', align: 'center', title: '描述'},
                {align: 'center', toolbar: '#menuGroupTableTmplBox', title: '操作', minWidth: 120}
            ]]
        });
        $("#treeTbTree").empty();
        dirrid = menuData.records[0].id;
        menuGroup = menuData.records[0]
        getTreeTable(menuData.records[0],function (resArr) {
            $.fn.zTree.init($("#treeTbTree"), setting.identValueSetting, resArr);
        });
        var divbox = $("#menuManage").next(".layui-table-view");
        $(divbox).find("table tr").eq(1).click();
        //第一次才渲染分页
        if(fistRenderPage){
            laypage.render({
                elem: 'page-box'
                ,count: menuData.total,
                limit:menuData.size,
                groups:1,
                current:current
                ,layout: ['count','prev','page', 'next']
                ,jump: function(obj, first){
                    if(!first){
                        current = obj.curr;
                        fistRenderPage = false;
                        getMenuGroupList();
                    }
                }
            });
        }
    }
    //获取树形目录的值
    function getTreeTable(obj,callback) {
        let parcode = obj.code?obj.code:'root';
        axios({
            method: 'get',
            url:metadataUrl.menuManage.menuTree.menuTreeList+'/'+ dirrid + '/' + parcode,
            headers:{
                'Authorization':Authorization
            }
        })
            .then(function (response) {
                if(response.status == 200 &&response.data.message == "success"){
                    var data = response.data.data;
                    var resArr = [];
                    zhuanHuanTree(data,resArr);
                    parCode = '';
                    par_id = '';
                    menuDetails = {};
                    // IdentValueTree = resArr;
                    callback(resArr)

                }
            })
            .catch(function (error) {
                console.log(error);
            });
    }
    //转换菜单集合数据
    function zhuanHuanTree(tdata,resData) {
        if(Array.isArray(tdata) && tdata.length>0){
            tdata.forEach(function(v,i){
                var newValue=v.name;
                resData[i]=v;
                resData[i].title=newValue;
                resData[i].icon = "";
                resData[i].isParent = "true";
                resData[i].sub = [];
            });
        }
    }

    //查询下方区划树的下级区划值（懒加载）
    function onExpandIdentValueTree(event, treeId, treeNode) {

        if(treeNode.sub.length>0||treeNode.hasChild=='0'){
            return false
        }
        getTreeTable(treeNode,function (resArr) {
            const treeObj = $.fn.zTree.getZTreeObj("treeTbTree");
            treeNode = treeObj.addNodes(treeNode,resArr);


        });
    }
    //选中分组值
    function identValueOnClick(event, treeId, treeNode){
        menuDetails = treeNode
        parCode = treeNode.code
        par_id = treeNode.id
        IdentValueSelected = treeNode;
    }
    //控制目录分组权限
    function getMenuGroupPower() {
        var str = template("menuGroup-tmpl",{});
        document.getElementById("menuGroup-tmpl-box").innerHTML = str;

        var str = template("menuGroupTableTmpl",{});
        document.getElementById("menuGroupTableTmplBox").innerHTML = str;
    }

    //控制目录值权限
    function getMenuValuePower() {
        var str = template("menuValue-tmpl",{});
        document.getElementById("menuValue-tmpl-box").innerHTML = str;
    }

    // 删除目录分组
    function doDelMenuGroup(obj) {
        layer.confirm('确定要删除“' + obj.data.name + '”角色吗？', {
            skin: 'layui-layer-admin',
            shade: .1
        }, function (i) {
            layer.close(i);
            layer.load(2);
            axios({
                method: 'delete',
                url:metadataUrl.menuManage.menuGroup.deleteMenuGroup + obj.data.id,
                headers:{
                    'Authorization':Authorization
                }
            })
                .then(function (res) {
                    if (res.status == 200&&res.data.message=="success") {
                        layer.closeAll('loading');
                        layer.msg("成功删除", {icon: 1});
                        fistRenderPage = true;
                        getMenuGroupList();
                    } else {
                        layer.msg(res.data.message, {icon: 2});
                        layer.closeAll('loading');
                    }
                })
                .catch(function (err) {
                    console.log(err);
                })
        });
    }

    // 显示编辑目录分组弹窗
    function showEditModel(mRole) {
        admin.open({
            type: 1,
            title: '编辑目录分组',
            area: ['350px', '350px'],
            offset:'auto',
            content: $('#editMenuGroupModel').html(),
            success: function (layero, dIndex) {
                form.val('modelUserForm', mRole);  // 回显数据
                // 表单提交事件
                form.on('submit(modelSubmitUser)', function (data) {
                    layer.load(2);
                    let formData = mRole;
                    formData.name = data.field.name;
                    formData.memo = data.field.memo;
                    axios({
                        method: 'put',
                        data:formData,
                        url:metadataUrl.menuManage.menuGroup.editMenuGroup,
                        headers:{
                            'Authorization':Authorization
                        }
                    })
                        .then(function (res) {
                            if (res.status == 200&&res.data.message=="success") {
                                getMenuGroupList();
                                layer.closeAll('loading');
                                layer.close(dIndex);
                                layer.msg("编辑成功", {icon: 1});
                            } else {
                                layer.msg(res.data.message, {icon: 2});
                                layer.closeAll('loading');
                            }
                        })
                        .catch(function (err) {
                            console.log(err);
                        })
                    return false;
                });
            }
        });
    }

    //显示新增目录分组弹窗
    function addMenuGroupModel() {
        admin.open({
            type: 1,
            title: '新增目录分组',
            area: ['350px', '350px'],
            offset:'auto',
            content: $('#addMenuGroupForm').html(),
            success: function (layero, dIndex) {
                // 表单提交事件
                form.on('submit(modelSubmitUser)', function (data) {
                    layer.load(2);
                    let formData = data.field;
                    axios({
                        method: 'post',
                        data:formData,
                        url:metadataUrl.menuManage.menuGroup.addMenuGroup,
                        headers:{
                            'Authorization':Authorization
                        }
                    })
                        .then(function (res) {
                            if (res.status == 200&&res.data.message=="success") {
                                fistRenderPage = true;
                                getMenuGroupList();
                                layer.closeAll('loading');
                                layer.close(dIndex);
                                layer.msg("新增成功", {icon: 1});
                            } else {
                                layer.msg(res.data.message, {icon: 2});
                                layer.closeAll('loading');
                            }
                        })
                        .catch(function (err) {
                            console.log(err);
                        })
                    return false;
                });

            }
        });
    }

    //新增目录值弹窗
    function showAddMenuValueModel() {
        admin.open({
            type: 1,
            title: '新增目录值',
            area: ['350px', '350px'],
            offset:'auto',
            content: $('#addMenuValueModel').html(),
            success: function (layero, dIndex) {
                // 表单提交事件
                form.on('submit(addMenuValue)', function (data) {
                    layer.load(2);
                    let formData = data.field;
                    formData.dirrid = dirrid;
                    formData.parCode = parCode?parCode:'root';
                    formData.par_id = par_id?par_id:'root';
                    axios({
                        method: 'post',
                        data:formData,
                        url:metadataUrl.menuManage.menuTree.addMenuTree,
                        headers:{
                            'Authorization':Authorization
                        }
                    })
                        .then(function (res) {
                            if (res.status == 200&&res.data.message=="success") {
                                getTreeTable(menuGroup,function (resArr) {
                                    $.fn.zTree.init($("#treeTbTree"), setting.identValueSetting, resArr);
                                });
                                layer.closeAll('loading');
                                layer.close(dIndex);
                                layer.msg("新增成功", {icon: 1});
                            } else {
                                layer.msg(res.data.message, {icon: 2});
                                layer.closeAll('loading');
                            }
                        })
                        .catch(function (err) {
                            console.log(err);
                        })
                    return false;
                });
            }
        });
    }

    //编辑目录值弹窗
    function showEditMenuValueModel() {
        if(!menuDetails.id){
            layer.msg("请选择需要编辑的目录值", {icon: 2});
            return false;
        }
        admin.open({
            type: 1,
            title: '编辑目录值',
            area: ['350px', '350px'],
            offset:'auto',
            content: $('#editMenuValueModel').html(),
            success: function (layero, dIndex) {
                form.val('modelUserForm', menuDetails);  // 回显数据
                // 表单提交事件
                form.on('submit(editMenuValue)', function (data) {
                    menuDetails.name = data.field.name;
                    menuDetails.memo = data.field.memo;
                    axios({
                        method: 'put',
                        data:menuDetails,
                        url:metadataUrl.menuManage.menuTree.editMenuTree,
                        headers:{
                            'Authorization':Authorization
                        }
                    })
                        .then(function (res) {
                            if (res.status == 200&&res.data.message=="success") {
                                getTreeTable(menuGroup,function (resArr) {
                                    $.fn.zTree.init($("#treeTbTree"), setting.identValueSetting, resArr);
                                });
                                layer.closeAll('loading');
                                layer.close(dIndex);
                                layer.msg("编辑成功", {icon: 1});
                                parCode = '';
                                par_id = '';
                                menuDetails ={};
                            } else {
                                layer.msg(res.data.message, {icon: 2});
                                layer.closeAll('loading');
                            }
                        })
                        .catch(function (err) {
                            console.log(err);
                        })
                    return false;
                });
            }
        });
    }

    //删除目录值弹窗
    function showDeleteMenuValueModel() {
        if(!menuDetails.id){
            layer.msg("请选择需要删除的目录值", {icon: 2});
            return false;
        }
        layer.confirm('确定要删除目录值“'+ menuDetails.name + '”吗？', {
            skin: 'layui-layer-admin',
            shade: .1
        }, function (i) {
            layer.close(i);
            layer.load(2);
            axios({
                method: 'delete',
                url:metadataUrl.menuManage.menuTree.deleteMenuTree + menuDetails.id,
                headers:{
                    'Authorization':Authorization
                }
            })
                .then(function (res) {
                    if (res.status == 200&&res.data.message=="success") {
                        getTreeTable(menuGroup,function (resArr) {
                            $.fn.zTree.init($("#treeTbTree"), setting.identValueSetting, resArr);
                        });
                        layer.closeAll('loading');
                        layer.msg("成功删除", {icon: 1});
                        menuDetails = {};
                    } else {
                        layer.msg(res.data.message, {icon: 2});
                        layer.closeAll('loading');
                    }
                })
                .catch(function (err) {
                    console.log(err);
                })
        });
    }
});